// ============================== 导入依赖 ============================== //

// ============================== 导出文件工具 ============================== //

export default {
  /**
   * 文件上传
   *
   * @param {File} file 文件
   * @param {String} folder 目录
   * @param {String} business 业务
   *
   * @returns {String} 文件路径
   */
  async fileUpload(file, folder = 'file', business = 'public') {
    const { PREFIX, SUFFIX } = this.FILE
    const url = `${PREFIX}/upload${SUFFIX}`
    const param = getUploadParam(file, this.fileName(file), folder, business)
    const { subUrl } = await this.post('文件上传', url, param, this.FILE.META)
    return subUrl
  },

  /**
   * 3D文件上传
   *
   * @param {File} file 文件
   * @param {String} folder 目录
   * @param {String} type 类型 (file/image/video/audio)
   *
   * @returns {String} 图片路径
   */
  async _3DFileUpload(file, folder = 'file', business = 'public') {
    this.loading()
    const url = '/ib/config3d/v1/storage/config3dUpload'
    const param = getUploadParam(file, this.fileName(file), folder, business)
    const { subUrl } = await this.post('组态文件上传', url, param, this.FILE.META)
    this.unloading()
    return subUrl
  },

  /**
   * 文件地址
   *
   * @param {String} path  相对地址
   * @param {String} empty 空白文件
   *
   * @returns {String} 完整地址
   */
  _3Dfile(path, empty) {
    const { SUFFIX, EMPTY } = this.FILE || {}
    if (!path || !this.isString(path)) return empty === undefined ? EMPTY : empty
    if (/^http(s?):\/\//.test(path)) return `${path}?${this.VERSION}`

    const prefix = '/ib/config3d/v1/storage/access'
    const url = path.replace(/^\//, '').replace(prefix.slice(1), '')

    return `${prefix}/${url}${SUFFIX}?${this.VERSION}`
  },
}

/**
 * 获取上传参数
 *
 * @param {*} file 文件
 */
const getUploadParam = (file, name, folder, business = 'public') => {
  const formdata = new FormData()
  const subPaths = folder.replace(/(^\/)|(\/$)/g, '').replace(/\//g, ',')

  formdata.append('file', file) //  上传时的 blob 文件流
  formdata.append('uploadFileName', encodeURI(name)) // 上传文件名
  formdata.append('subPaths', subPaths) // 文件路径,多级用,隔开 如 aaa,bbb,ccc

  formdata.append('businessTag', business) // 业务标识
  formdata.append('uploadType', 3) // 上传类型 1 新建 2 更新 3 强制(无则新建,有则更新) 默认1
  formdata.append('type', 1) // 文件类型 1 文件 2 base64; 默认 1

  return formdata
}
